package cn.itsource.realm;

import cn.itsource.crm.domain.MyUser;
import cn.itsource.crm.mapper.MyUserMapper;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm
 *
 * 如果bean交给了spring管理，该bean内部可以任意注入spring管理的bean
 */
public class ItsourceRealm extends AuthorizingRealm {

    @Autowired
    private MyUserMapper myUserMapper;
//
//    @Autowired
//    private IPermissionService permissionService;

    /**
     * 授权方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //动态获取当前登陆的权限
//        Set<String> permissions = permissionService.findPermissionsnByLoginUser();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //授权
        info.setStringPermissions(null);
        return info;
    }

    /**
     * 认证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取到用户名
        String username = (String) authenticationToken.getPrincipal();
        //根据用户名到数据库中查询对象
        MyUser user = myUserMapper.findByEmail(username);
        if(user == null){
            return null;//底层会自动抛出异常，未知账号异常
        }
        //盐值
        ByteSource salt = ByteSource.Util.bytes(user.getEmail());
        return new SimpleAuthenticationInfo(user,user.getPassword(),salt,super.getName());
    }
}
